#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
反取证和数据混淆系统
当被蓝队发现后，激活反取证机制防止数字取证分析

反取证技术：
1. 时间戳混淆
2. 文件系统反取证
3. 内存反取证
4. 网络痕迹混淆
5. 日志污染
6. 元数据伪造
7. 数据碎片化
8. 虚假证据植入
"""

import os
import sys
import time
import random
import string
import hashlib
import subprocess
import tempfile
import shutil
from datetime import datetime, timedelta
from pathlib import Path
import json

class AntiForensicsSystem:
    def __init__(self):
        self.start_time = time.time()
        self.fake_timestamps = []
        self.decoy_files = []
        self.log_entries = []
        
    def log_action(self, action, status="SUCCESS"):
        """记录反取证操作"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        entry = {
            "timestamp": timestamp,
            "action": action,
            "status": status
        }
        self.log_entries.append(entry)
        print(f"[{timestamp}] {action} - {status}")
    
    def execute_command(self, cmd, timeout=10):
        """安全执行命令"""
        try:
            result = subprocess.run(cmd, shell=True, capture_output=True, 
                                  text=True, timeout=timeout)
            return result.returncode == 0, result.stdout, result.stderr
        except subprocess.TimeoutExpired:
            return False, "", "命令超时"
        except Exception as e:
            return False, "", str(e)
    
    def timestamp_confusion(self):
        """时间戳混淆"""
        self.log_action("启动时间戳混淆", "RUNNING")
        
        try:
            # 生成虚假时间戳范围（过去6个月）
            base_time = time.time() - (180 * 24 * 3600)  # 6个月前
            
            # 收集所有文件
            all_files = []
            for root, dirs, files in os.walk('.'):
                for file in files:
                    file_path = os.path.join(root, file)
                    if os.path.exists(file_path):
                        all_files.append(file_path)
            
            # 随机修改文件时间戳
            modified_count = 0
            for file_path in all_files:
                try:
                    # 生成随机时间戳
                    random_offset = random.randint(0, 180 * 24 * 3600)
                    fake_time = base_time + random_offset
                    
                    # 修改访问时间和修改时间
                    os.utime(file_path, (fake_time, fake_time))
                    
                    self.fake_timestamps.append({
                        "file": file_path,
                        "fake_time": fake_time,
                        "fake_date": datetime.fromtimestamp(fake_time).isoformat()
                    })
                    
                    modified_count += 1
                    
                except Exception as e:
                    continue
            
            self.log_action(f"时间戳混淆完成，修改了 {modified_count} 个文件", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"时间戳混淆失败: {e}", "FAILED")
    
    def filesystem_anti_forensics(self):
        """文件系统反取证"""
        self.log_action("启动文件系统反取证", "RUNNING")
        
        try:
            # 1. 创建大量虚假文件
            self.create_decoy_files()
            
            # 2. 文件碎片化
            self.fragment_files()
            
            # 3. 覆写已删除文件的磁盘空间
            self.overwrite_deleted_space()
            
            # 4. 修改文件系统元数据
            self.modify_filesystem_metadata()
            
            self.log_action("文件系统反取证完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"文件系统反取证失败: {e}", "FAILED")
    
    def create_decoy_files(self):
        """创建诱饵文件"""
        self.log_action("创建诱饵文件", "RUNNING")
        
        try:
            # 创建虚假的系统管理文件
            decoy_templates = {
                "system_monitor.py": self.generate_fake_monitor_script(),
                "network_check.sh": self.generate_fake_network_script(),
                "log_analyzer.py": self.generate_fake_analyzer_script(),
                "backup_tool.py": self.generate_fake_backup_script(),
                "security_scan.py": self.generate_fake_security_script()
            }
            
            # 在多个目录创建诱饵文件
            decoy_dirs = ['tools', 'scripts', 'utils', 'admin']
            
            for dir_name in decoy_dirs:
                if not os.path.exists(dir_name):
                    os.makedirs(dir_name)
                
                for filename, content in decoy_templates.items():
                    file_path = os.path.join(dir_name, filename)
                    
                    with open(file_path, 'w') as f:
                        f.write(content)
                    
                    # 设置旧的时间戳
                    old_time = time.time() - random.randint(30, 180) * 24 * 3600
                    os.utime(file_path, (old_time, old_time))
                    
                    self.decoy_files.append(file_path)
            
            # 创建虚假的配置文件
            fake_configs = {
                "monitor.conf": "[settings]\ninterval=300\nlog_level=INFO\n",
                "network.ini": "[network]\ninterface=eth0\ntimeout=30\n",
                "backup.json": '{"schedule": "daily", "retention": 30}'
            }
            
            for filename, content in fake_configs.items():
                with open(filename, 'w') as f:
                    f.write(content)
                
                old_time = time.time() - random.randint(60, 365) * 24 * 3600
                os.utime(filename, (old_time, old_time))
                self.decoy_files.append(filename)
            
            self.log_action(f"创建了 {len(self.decoy_files)} 个诱饵文件", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"诱饵文件创建失败: {e}", "FAILED")
    
    def generate_fake_monitor_script(self):
        """生成虚假的监控脚本"""
        return '''#!/usr/bin/env python3
"""
系统监控工具
监控系统资源使用情况
"""

import os
import time
import psutil

def monitor_system():
    while True:
        cpu_percent = psutil.cpu_percent()
        memory = psutil.virtual_memory()
        
        print(f"CPU使用率: {cpu_percent}%")
        print(f"内存使用率: {memory.percent}%")
        
        time.sleep(60)

if __name__ == "__main__":
    monitor_system()
'''
    
    def generate_fake_network_script(self):
        """生成虚假的网络脚本"""
        return '''#!/bin/bash
# 网络连接检查工具

echo "检查网络连接状态..."

ping -c 4 8.8.8.8
ping -c 4 google.com

netstat -tuln
ss -tuln

echo "网络检查完成"
'''
    
    def generate_fake_analyzer_script(self):
        """生成虚假的分析脚本"""
        return '''#!/usr/bin/env python3
"""
日志分析工具
分析系统日志文件
"""

import re
import os
from datetime import datetime

def analyze_logs():
    log_files = ['/var/log/syslog', '/var/log/auth.log']
    
    for log_file in log_files:
        if os.path.exists(log_file):
            print(f"分析日志文件: {log_file}")
            # 简单的日志分析逻辑
            with open(log_file, 'r') as f:
                lines = f.readlines()
                print(f"总行数: {len(lines)}")

if __name__ == "__main__":
    analyze_logs()
'''
    
    def generate_fake_backup_script(self):
        """生成虚假的备份脚本"""
        return '''#!/usr/bin/env python3
"""
系统备份工具
定期备份重要文件
"""

import os
import shutil
import datetime

def backup_files():
    backup_dir = f"/backup/{datetime.date.today()}"
    
    if not os.path.exists(backup_dir):
        os.makedirs(backup_dir)
    
    important_dirs = ['/etc', '/home']
    
    for dir_path in important_dirs:
        if os.path.exists(dir_path):
            print(f"备份目录: {dir_path}")
            # 这里只是示例，不会真正备份

if __name__ == "__main__":
    backup_files()
'''
    
    def generate_fake_security_script(self):
        """生成虚假的安全脚本"""
        return '''#!/usr/bin/env python3
"""
安全扫描工具
检查系统安全状态
"""

import os
import subprocess

def security_scan():
    print("开始安全扫描...")
    
    # 检查开放端口
    result = subprocess.run(['netstat', '-tuln'], capture_output=True, text=True)
    print("开放端口检查完成")
    
    # 检查运行进程
    result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
    print("进程检查完成")
    
    print("安全扫描完成")

if __name__ == "__main__":
    security_scan()
'''
    
    def fragment_files(self):
        """文件碎片化"""
        self.log_action("执行文件碎片化", "RUNNING")
        
        try:
            # 创建大量小文件来增加文件系统碎片
            fragment_dir = "fragments"
            if not os.path.exists(fragment_dir):
                os.makedirs(fragment_dir)
            
            for i in range(1000):
                fragment_file = os.path.join(fragment_dir, f"frag_{i:04d}.tmp")
                
                # 写入随机数据
                with open(fragment_file, 'wb') as f:
                    f.write(os.urandom(random.randint(1024, 8192)))
                
                # 随机时间戳
                random_time = time.time() - random.randint(0, 365 * 24 * 3600)
                os.utime(fragment_file, (random_time, random_time))
            
            self.log_action("文件碎片化完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"文件碎片化失败: {e}", "FAILED")
    
    def overwrite_deleted_space(self):
        """覆写已删除文件的磁盘空间"""
        self.log_action("覆写已删除文件空间", "RUNNING")
        
        try:
            # 创建临时大文件填充空闲空间
            temp_dir = tempfile.mkdtemp()
            temp_file = os.path.join(temp_dir, 'overwrite.tmp')
            
            try:
                with open(temp_file, 'wb') as f:
                    # 写入随机数据直到磁盘满
                    chunk_size = 1024 * 1024  # 1MB
                    while True:
                        f.write(os.urandom(chunk_size))
            except OSError:
                # 磁盘满了，这是预期的
                pass
            
            # 删除临时文件
            if os.path.exists(temp_file):
                os.remove(temp_file)
            os.rmdir(temp_dir)
            
            self.log_action("磁盘空间覆写完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"磁盘空间覆写失败: {e}", "FAILED")
    
    def modify_filesystem_metadata(self):
        """修改文件系统元数据"""
        self.log_action("修改文件系统元数据", "RUNNING")
        
        try:
            # 在Linux系统上修改文件属性
            if os.name == 'posix':
                # 尝试修改文件的扩展属性
                for root, dirs, files in os.walk('.'):
                    for file in files[:10]:  # 只修改前10个文件
                        file_path = os.path.join(root, file)
                        try:
                            # 添加虚假的扩展属性
                            self.execute_command(f'setfattr -n user.comment -v "system_file" "{file_path}"')
                            self.execute_command(f'setfattr -n user.origin -v "system_admin" "{file_path}"')
                        except:
                            pass
            
            self.log_action("文件系统元数据修改完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"文件系统元数据修改失败: {e}", "FAILED")
    
    def memory_anti_forensics(self):
        """内存反取证"""
        self.log_action("启动内存反取证", "RUNNING")
        
        try:
            # 1. 内存污染
            self.pollute_memory()
            
            # 2. 清理内存缓存
            self.clear_memory_cache()
            
            # 3. 创建虚假内存模式
            self.create_fake_memory_patterns()
            
            self.log_action("内存反取证完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"内存反取证失败: {e}", "FAILED")
    
    def pollute_memory(self):
        """内存污染"""
        try:
            # 分配大量内存并填充随机数据
            memory_chunks = []
            
            for i in range(100):
                chunk = bytearray(1024 * 1024)  # 1MB
                for j in range(0, len(chunk), 4):
                    chunk[j:j+4] = os.urandom(4)
                memory_chunks.append(chunk)
            
            # 保持一段时间后释放
            time.sleep(5)
            del memory_chunks
            
            self.log_action("内存污染完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"内存污染失败: {e}", "FAILED")
    
    def clear_memory_cache(self):
        """清理内存缓存"""
        try:
            # 清理系统缓存
            self.execute_command("sync")
            self.execute_command("echo 3 > /proc/sys/vm/drop_caches")
            
            # 强制垃圾回收
            import gc
            gc.collect()
            
            self.log_action("内存缓存清理完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"内存缓存清理失败: {e}", "FAILED")
    
    def create_fake_memory_patterns(self):
        """创建虚假内存模式"""
        try:
            # 创建看起来像正常系统进程的内存模式
            fake_patterns = [
                b"systemd",
                b"kernel",
                b"init",
                b"NetworkManager",
                b"sshd",
                b"cron"
            ]
            
            # 在内存中重复这些模式
            for pattern in fake_patterns:
                data = pattern * 1000
                # 短暂保存在内存中
                time.sleep(0.1)
                del data
            
            self.log_action("虚假内存模式创建完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"虚假内存模式创建失败: {e}", "FAILED")
    
    def network_trace_confusion(self):
        """网络痕迹混淆"""
        self.log_action("启动网络痕迹混淆", "RUNNING")
        
        try:
            # 1. 清理网络缓存
            self.clear_network_cache()
            
            # 2. 生成虚假网络流量
            self.generate_fake_traffic()
            
            # 3. 修改网络配置历史
            self.modify_network_history()
            
            self.log_action("网络痕迹混淆完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"网络痕迹混淆失败: {e}", "FAILED")
    
    def clear_network_cache(self):
        """清理网络缓存"""
        try:
            # 清理ARP缓存
            self.execute_command("arp -d -a")
            
            # 清理DNS缓存
            self.execute_command("systemctl flush-dns")
            
            # 清理路由缓存
            self.execute_command("ip route flush cache")
            
            # 清理连接跟踪
            self.execute_command("conntrack -F")
            
            self.log_action("网络缓存清理完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"网络缓存清理失败: {e}", "FAILED")
    
    def generate_fake_traffic(self):
        """生成虚假网络流量"""
        try:
            # 生成到正常网站的连接
            normal_sites = [
                "google.com",
                "github.com",
                "stackoverflow.com",
                "ubuntu.com",
                "python.org"
            ]
            
            for site in normal_sites:
                self.execute_command(f"ping -c 3 {site}")
                self.execute_command(f"nslookup {site}")
            
            self.log_action("虚假网络流量生成完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"虚假网络流量生成失败: {e}", "FAILED")
    
    def modify_network_history(self):
        """修改网络配置历史"""
        try:
            # 创建虚假的网络配置文件
            fake_network_configs = {
                "/tmp/network_backup.conf": """
auto eth0
iface eth0 inet dhcp
""",
                "/tmp/hosts_backup": """
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
"""
            }
            
            for config_file, content in fake_network_configs.items():
                with open(config_file, 'w') as f:
                    f.write(content)
                
                # 设置旧时间戳
                old_time = time.time() - random.randint(30, 365) * 24 * 3600
                os.utime(config_file, (old_time, old_time))
            
            self.log_action("网络配置历史修改完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"网络配置历史修改失败: {e}", "FAILED")
    
    def log_pollution(self):
        """日志污染"""
        self.log_action("启动日志污染", "RUNNING")
        
        try:
            # 生成大量正常的日志条目
            fake_log_entries = [
                "User admin logged in successfully",
                "System backup completed",
                "Network interface eth0 up",
                "Cron job executed successfully",
                "System update check completed",
                "SSH connection from 192.168.1.100",
                "File system check completed",
                "Service httpd started",
                "Database backup completed",
                "Security scan completed"
            ]
            
            # 写入虚假日志
            log_file = "system_activity.log"
            with open(log_file, 'w') as f:
                for i in range(1000):
                    timestamp = datetime.now() - timedelta(days=random.randint(1, 30))
                    entry = random.choice(fake_log_entries)
                    f.write(f"{timestamp.isoformat()} INFO {entry}\n")
            
            # 设置旧时间戳
            old_time = time.time() - 30 * 24 * 3600
            os.utime(log_file, (old_time, old_time))
            
            self.log_action("日志污染完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"日志污染失败: {e}", "FAILED")
    
    def metadata_forgery(self):
        """元数据伪造"""
        self.log_action("启动元数据伪造", "RUNNING")
        
        try:
            # 创建虚假的系统信息文件
            fake_system_info = {
                "system_info.json": {
                    "hostname": "admin-workstation",
                    "os": "Ubuntu 20.04 LTS",
                    "kernel": "5.4.0-74-generic",
                    "uptime": "15 days",
                    "users": ["admin", "backup", "monitor"]
                },
                "hardware_info.json": {
                    "cpu": "Intel Core i7-8700K",
                    "memory": "32GB DDR4",
                    "storage": "1TB SSD",
                    "network": "Gigabit Ethernet"
                }
            }
            
            for filename, data in fake_system_info.items():
                with open(filename, 'w') as f:
                    json.dump(data, f, indent=2)
                
                # 设置旧时间戳
                old_time = time.time() - random.randint(60, 365) * 24 * 3600
                os.utime(filename, (old_time, old_time))
            
            self.log_action("元数据伪造完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"元数据伪造失败: {e}", "FAILED")
    
    def plant_false_evidence(self):
        """植入虚假证据"""
        self.log_action("植入虚假证据", "RUNNING")
        
        try:
            # 创建看起来像被攻击的痕迹
            false_evidence = {
                "security_alert.log": """
2024-01-15 10:30:15 ALERT Failed login attempt from 192.168.1.50
2024-01-15 10:30:45 ALERT Failed login attempt from 192.168.1.50
2024-01-15 10:31:15 ALERT Failed login attempt from 192.168.1.50
2024-01-15 10:35:22 INFO Login successful for user admin from 192.168.1.100
2024-01-15 11:00:00 INFO System scan completed - no threats found
""",
                "incident_report.txt": """
安全事件报告
日期: 2024-01-15
事件: 检测到来自外部IP的暴力破解尝试
状态: 已阻止
措施: 已加强防火墙规则
""",
                "forensic_notes.txt": """
取证分析笔记
- 检查了系统日志，发现正常的管理活动
- 网络流量分析显示正常的业务通信
- 文件完整性检查通过
- 未发现恶意软件或后门
结论: 系统安全，无异常活动
"""
            }
            
            for filename, content in false_evidence.items():
                with open(filename, 'w') as f:
                    f.write(content)
                
                # 设置合理的时间戳
                evidence_time = time.time() - random.randint(7, 30) * 24 * 3600
                os.utime(filename, (evidence_time, evidence_time))
            
            self.log_action("虚假证据植入完成", "SUCCESS")
            
        except Exception as e:
            self.log_action(f"虚假证据植入失败: {e}", "FAILED")
    
    def generate_final_report(self):
        """生成最终报告"""
        try:
            total_time = time.time() - self.start_time
            
            report = {
                "anti_forensics_report": {
                    "execution_time": f"{total_time:.2f}秒",
                    "start_time": datetime.fromtimestamp(self.start_time).isoformat(),
                    "end_time": datetime.now().isoformat(),
                    "operations_completed": len([entry for entry in self.log_entries if entry["status"] == "SUCCESS"]),
                    "operations_failed": len([entry for entry in self.log_entries if entry["status"] == "FAILED"]),
                    "fake_timestamps_created": len(self.fake_timestamps),
                    "decoy_files_created": len(self.decoy_files),
                    "detailed_log": self.log_entries
                }
            }
            
            with open("anti_forensics_report.json", 'w') as f:
                json.dump(report, f, indent=2, ensure_ascii=False)
            
            self.log_action("反取证报告生成完成", "SUCCESS")
            return report
            
        except Exception as e:
            self.log_action(f"报告生成失败: {e}", "FAILED")
            return None
    
    def run_full_anti_forensics(self):
        """运行完整的反取证流程"""
        print("🔒" + "="*50)
        print("🔒 反取证和数据混淆系统")
        print("🔒 开始执行反取证操作...")
        print("🔒" + "="*50)
        
        # 执行反取证步骤
        anti_forensics_steps = [
            ("时间戳混淆", self.timestamp_confusion),
            ("文件系统反取证", self.filesystem_anti_forensics),
            ("内存反取证", self.memory_anti_forensics),
            ("网络痕迹混淆", self.network_trace_confusion),
            ("日志污染", self.log_pollution),
            ("元数据伪造", self.metadata_forgery),
            ("植入虚假证据", self.plant_false_evidence)
        ]
        
        for step_name, step_func in anti_forensics_steps:
            try:
                print(f"\n📋 执行: {step_name}")
                step_func()
                print(f"✅ 完成: {step_name}")
            except Exception as e:
                print(f"❌ 失败: {step_name} - {e}")
        
        # 生成最终报告
        print(f"\n📊 生成反取证报告...")
        report = self.generate_final_report()
        
        total_time = time.time() - self.start_time
        
        print("\n" + "="*50)
        print("📊 反取证操作完成总结")
        print("="*50)
        print(f"⏱️  总执行时间: {total_time:.2f}秒")
        print(f"✅ 成功操作: {len([e for e in self.log_entries if e['status'] == 'SUCCESS'])}")
        print(f"❌ 失败操作: {len([e for e in self.log_entries if e['status'] == 'FAILED'])}")
        print(f"🕐 时间戳混淆: {len(self.fake_timestamps)} 个文件")
        print(f"🎭 诱饵文件: {len(self.decoy_files)} 个")
        print("🔒 反取证机制已激活")
        print("⚠️  建议立即执行数据销毁")
        print("="*50)

def main():
    """主函数"""
    anti_forensics = AntiForensicsSystem()
    anti_forensics.run_full_anti_forensics()

if __name__ == "__main__":
    main()